<!--
 * @Author: actor
 * @Date: 2023-11-27 16:55:57
 * @email: 395593455@qq.com
 * @LastEditors: actor
 * @LastEditTime: 2023-12-19 16:10:49
 * @FilePath: \i-hos-app\shared\emr\src\views\tmpl\TmplEdit.vue
 * @Description: 电子病历编辑主页面
-->
<template>
  <div class="emrEditPage">
    <!-- 头部表单 -->
    <SerachForm class="serachForm" :serachKey="serachKey">
      <div :style="{ flexWrap: 'nowrap', display: 'flex' }">
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button
          @click="
            () => {
              $emit('back')
            }
          "
          >返回</el-button
        >
      </div>
    </SerachForm>

    <!-- 电子病历编辑器 -->
    <EmrEditer type="design" :docTempJson="tempJson.docTempJson"></EmrEditer>
  </div>
</template>

<script setup lang="ts">
  import { ref, Ref, reactive, getCurrentInstance, watch, nextTick } from 'vue'
  import { useRouter, useRoute, Router, RouteLocationNormalizedLoaded } from 'vue-router'
  import { ElMessage } from 'element-plus'

  // 自定义组件
  import SerachForm from '../../components/common/serachForm.vue'
  import EmrEditer from '../editer/EmrEditer.vue'

  // 配置类型约束
  import { IPageShare, ISerachKey } from '../../interface/pageShare'
  import { ISetPaperState } from '../../interface/set'
  import { IPageConfigStore } from '../../interface/page'
  // 仓库数据以及解构store的配置数据
  import { usePageConfigStore } from '../../store/pageConfig'
  import { useEmrPageShare } from '../../store/emrPageShare'
  import { usePaperSetStore } from '../../store/paperSet'
  const configStore: IPageConfigStore = usePageConfigStore()
  const emrPageShare: IPageShare = useEmrPageShare()
  const paperSetStore: ISetPaperState = usePaperSetStore()
  const { proxy } = getCurrentInstance() as any

  // 接收父组件值
  const props = defineProps({
    docTempJson: {
      type: String,
      default: '',
    },
  })

  // 更新父组件方法
  let $emit = defineEmits<{
    (e: 'back'): void
  }>()

  let router: Router = useRouter(),
    // route: RouteLocationNormalizedLoaded = useRoute(),
    tempJson: Ref<any> = ref({}),
    serachKey: ISerachKey[] = reactive([
      // 分类对应的表格查询关键字
      { label: '归属机构', type: 'dropDown', value: '', list: [] },
      { label: '分类', type: 'dropDown', value: '', list: [] },
      {
        label: '状态',
        type: 'dropDown',
        value: '',
        list: [
          { label: '正常', value: 1 },
          { label: '停用', value: 0 },
        ],
      },
      { label: '标题', type: 'text', value: '' },
    ])

  // 处理机构蔬菜数据
  const changeDrganization = (tree: any) => {
    for (let item of tree) {
      item.label = item.deptName
      item.value = item.deptId
      // 遍历当前节点的子节点
      if (item.childList && item.childList.length) {
        item.children = []
        item.childList.forEach((childNode: any) => {
          childNode.label = childNode.deptName
          childNode.value = childNode.deptId
          item.children.push(childNode)
          if (childNode.childList && childNode.childList.length) {
            changeDrganization(childNode.childList) // 递归遍历子节点
          }
        })
      }
    }
    return tree
  }

  // 筛选科室分类
  const filterDictStore = (): void => {
    for (let obj of JSON.parse(window.sessionStorage.DictStore).baseDict) {
      serachKey[1].list = []
      nextTick(() => {
        if (obj.dictCode == 'FH0135') {
          serachKey[1].list.push({
            label: obj.dictItemName,
            value: obj.dictItemCode,
          })
        }
      })
    }
  }
  // 筛选机构分类
  const filterDrganization = (data: any): void => {
    serachKey[0].list = changeDrganization(data)
    // serachKey[0].list =[]
    // for (let obj of data) {
    //   serachKey[0].list.push({
    //     label: obj.deptName,
    //     value: obj.deptId,
    //   })
    // }
  }
  // 保存模板
  const handleSave = (): void => {
    let tmplSetup = {
      paperSet: paperSetStore._emr_paper_set,
      json: configStore.json,
      head: (document.querySelector('#emr_page_head')?.firstChild as Element).innerHTML,
      body: (document.querySelector('#emr_page_body')?.firstChild as Element).innerHTML,
      footer: (document.querySelector('#emr_page_footer')?.firstChild as Element).innerHTML,
    }
    let params = {
      deptId: serachKey[0].value, // 科室id
      docTempId: !!tempJson && !!tempJson.value.docTempId ? tempJson.value.docTempId : '', // 模板id(编辑传，新增不传)
      docTempJson: JSON.stringify(tmplSetup), // 模板(模板html，模板数据结构)
      docTempName: serachKey[3].value, // 模板名称
      docTempStatus: serachKey[2].value, // 文书状态 0停用 1正常
      docTempType: serachKey[1].value, // 文书类型（科室分类）
      docTempParentId: '', // 父级id
      orgId: '', // 机构id
    }
    let url: string = APP_GLOBAL.API['EMR']['emr-template-saveOrUpdate']
    proxy.$http.requestJSON('post', url, params).then((res: any) => {
      ElMessage({
        message: res.message,
        grouping: true,
        type: 'success',
      })
      if (res.message.includes('成功')) setTimeout(() => $emit('back'), 500)
    })
  }

  // 监听对应的值及更新
  watch(
    (): string => props.docTempJson,
    (): void => {
      if (!emrPageShare.organTreeList.length) {
        const Url: String = APP_GLOBAL.API['EMR']['category-organization']
        proxy.$http.requestJSON('post', Url).then((res: any) => {
          if (!!res.data.length) filterDrganization(res.data)
        })
      } else {
        filterDrganization(emrPageShare.organTreeList)
      }
      filterDictStore()
      if (!!props.docTempJson) {
        let queryData = JSON.parse(props.docTempJson as string)
        tempJson.value = queryData
        serachKey[0].value = queryData.deptId
        serachKey[1].value = queryData.docTempType
        serachKey[2].value = Number(queryData.docTempStatus)
        serachKey[3].value = queryData.docTempName
        configStore.$patch?.((state: IPageConfigStore) => {
          state.json = JSON.parse(queryData.docTempJson).json
        })
      } else {
        tempJson.value = {}
        serachKey[0].value = ''
        serachKey[1].value = ''
        serachKey[2].value = ''
        serachKey[3].value = ''
        configStore.$patch?.((state: IPageConfigStore) => {
          state.json = {
            HEADER: {},
            BODY: {},
            FOOTER: {},
          }
        })
      }
    },
    {
      immediate: true,
      deep: true,
    }
  )
</script>

<style scoped lang="scss">
  .emrEditPage {
    height: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    .serachForm {
      padding: 20px 10px 0 10px;
      // background-color: #f5f5f5;
      border-bottom: 1px solid #e4e7ed;
    }
    :deep(.emr .emr_container) {
      height: calc(100% - 107px);
    }
  }
</style>
